package com.mystnihon.tdroid.view;

import org.json.mine.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import ca.benow.transmission.model.TorrentStatus;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.mystnihon.tdroid.R;
import com.mystnihon.tdroid.view.fragment.TorrentFileFragment;

public class TorrentActivity extends SherlockFragmentActivity {
	public static final String TORRENT_JSON = "torrent_json";
	private static final int NUM_ITEMS = 1;

	private MyPagerAdapter mAdapter;
	private ViewPager mPager;
	private OnPageChangeListener mMyPageSelected;
	private TorrentFileFragment mFileFragment;
	private TorrentStatus mTorrentStatus;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_details);
		initTorrent();
		initFragment();
		initView();
	}

	private void initView() {
		mAdapter = new MyPagerAdapter(getSupportFragmentManager());
		mPager = (ViewPager) findViewById(R.id.pager_details);
		mPager.setAdapter(mAdapter);
		mPager.setOnPageChangeListener(mMyPageSelected);
	}

	private void initFragment() {
		mFileFragment = new TorrentFileFragment(mTorrentStatus);
	}

	private void initTorrent() {
		Intent intent = getIntent();
		if (intent != null) {
			String json = intent.getStringExtra(TORRENT_JSON);
			if (json != null && json.length() > 0) {
				mTorrentStatus = new TorrentStatus(new JSONObject(json));
			}
		}
	}

	class MyPagerAdapter extends FragmentStatePagerAdapter {

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return NUM_ITEMS;
		}

		@Override
		public Fragment getItem(int position) {

			return mFileFragment;
		}
	}

	class MyPageListener extends SimpleOnPageChangeListener {
		ActionBar bar;

		public MyPageListener(ActionBar actionbar) {
			bar = actionbar;
		}

		@Override
		public void onPageSelected(int position) {
			bar.setSelectedNavigationItem(position);

		}

	}

}
